<template>
  <div class="order-payment-container">
    <div class="payment-header">
      <h2>订单支付</h2>
      <div class="breadcrumb">
        <router-link to="/" class="breadcrumb-item">首页</router-link>
        <i class="el-icon-arrow-right"></i>
        <span class="breadcrumb-item active">订单支付</span>
      </div>
    </div>

    <el-card class="payment-card">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="error-container">
        <el-alert
          :title="error"
          type="error"
          show-icon
          :closable="false"
        />
        <el-button type="primary" @click="loadOrderInfo">重试</el-button>
        <el-button @click="$router.back()">返回</el-button>
      </div>

      <!-- 支付内容 -->
      <div v-else class="payment-content">
        <!-- 订单信息 -->
        <div class="order-info-section">
          <h3>订单信息</h3>
          <div class="info-item">
            <span class="label">订单编号：</span>
            <span class="value">{{ orderData.orderNo }}</span>
          </div>
          <div class="info-item">
            <span class="label">订单金额：</span>
            <span class="value amount">¥{{ orderData.actualAmount?.toFixed(2) }}</span>
          </div>
          <div class="info-item">
            <span class="label">优惠金额：</span>
            <span class="value discount">-¥{{ orderData.discountAmount?.toFixed(2) }}</span>
          </div>
          <div class="info-item">
            <span class="label">创建时间：</span>
            <span class="value">{{ formatDate(orderData.createdAt) }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付倒计时：</span>
            <span class="value countdown" :class="{ 'time-warning': remainingTime < 300 }">
              {{ formatTime(remainingTime) }}
            </span>
          </div>
          <!-- 余额信息 -->
          <div class="info-item">
            <span class="label">账户余额：</span>
            <span class="value balance">¥{{ userBalance?.toFixed(2) }}</span>
          </div>
        </div>

        <!-- 支付方式选择 -->
        <div class="payment-method-section">
          <h3>选择支付方式</h3>
          <el-radio-group v-model="selectedPaymentMethod" @change="onPaymentMethodChange">
            <el-radio-button label="BALANCE" :disabled="!canUseBalance">
              <i class="el-icon-wallet"></i> 余额支付
            </el-radio-button>
            <el-radio-button label="ALIPAY">
              <i class="el-icon-link"></i> 支付宝
            </el-radio-button>
          </el-radio-group>
          <div v-if="!canUseBalance" class="balance-warning">
            余额不足，请选择其他支付方式或进行充值
          </div>
        </div>

        <!-- 支付区域 - 余额支付 -->
        <div v-if="selectedPaymentMethod === 'BALANCE'" class="balance-payment-section">
          <el-form @submit.prevent="handleBalancePayment">
            <el-form-item label="支付确认" class="confirm-section">
              <span>确认使用余额支付 ¥{{ orderData.actualAmount?.toFixed(2) }}？</span>
              <el-button type="primary" @click="handleBalancePayment" :loading="processingPayment">
                确认支付
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 支付区域 - 支付宝 -->
        <div v-if="selectedPaymentMethod === 'ALIPAY'" class="alipay-payment-section">
          <div class="qr-code-container">
            <img v-if="qrCodeUrl" :src="qrCodeUrl" alt="支付宝支付二维码" class="qr-code" />
            <div v-else-if="processingPayment" class="loading-qr">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>生成支付二维码中...</span>
            </div>
            <div v-else class="qr-placeholder">
              <span>请选择支付宝支付并点击下方按钮生成二维码</span>
            </div>
          </div>
          <div class="payment-actions">
            <el-button type="primary" @click="generateAlipayQrCode" :loading="processingPayment">
              {{ qrCodeUrl ? '刷新二维码' : '生成二维码' }}
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 支付结果对话框 -->
    <el-dialog
      :title="paymentResult.title"
      :visible.sync="paymentResult.show"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="payment-result-content">
        <div class="result-icon" :class="paymentResult.success ? 'success' : 'error'">
          <el-icon v-if="paymentResult.success"><CircleCheckFilled /></el-icon>
          <el-icon v-else><CircleCloseFilled /></el-icon>
        </div>
        <div class="result-message">{{ paymentResult.message }}</div>
        <div class="result-detail" v-if="paymentResult.detail">{{ paymentResult.detail }}</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleResultClose">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { CircleCheckFilled, CircleCloseFilled, Loading } from '@element-plus/icons-vue'
import { createOrder, payOrder } from '@/api/order/order'
import { getAccountBalance } from '@/api/account/account'

export default defineComponent({
  name: 'OrderPayment',
  components: {
    CircleCheckFilled,
    CircleCloseFilled,
    Loading
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    
    // 响应式数据
    const loading = ref(false)
    const error = ref('')
    const orderData = ref({
      orderId: 0,
      orderNo: '',
      totalAmount: 0,
      discountAmount: 0,
      actualAmount: 0,
      createdAt: '',
      expireTime: ''
    })
    const userBalance = ref(0)
    const selectedPaymentMethod = ref('ALIPAY')
    const processingPayment = ref(false)
    const qrCodeUrl = ref('')
    const remainingTime = ref(1800) // 默认30分钟倒计时
    const countdownTimer = ref<number | null>(null)
    
    // 支付结果对话框
    const paymentResult = ref({
      show: false,
      success: false,
      title: '',
      message: '',
      detail: ''
    })

    // 计算属性
    const canUseBalance = computed(() => {
      return userBalance.value >= orderData.value.actualAmount
    })

    // 格式化时间
    const formatDate = (dateString: string) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }

    // 格式化倒计时
    const formatTime = (seconds: number) => {
      const mins = Math.floor(seconds / 60)
      const secs = seconds % 60
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
    }

    // 加载订单信息和用户余额
    const loadOrderInfo = async () => {
      loading.value = true
      error.value = ''
      
      try {
        // 获取URL参数
        const { itemType, itemId, couponId } = route.query
        
        if (!itemType || !itemId) {
          throw new Error('缺少必要的订单参数')
        }

        // 创建订单
        const orderResponse = await createOrder({
          type: itemType as 'COURSE' | 'TEST' | 'CONSULTATION',
          itemId: Number(itemId),
          couponId: couponId ? Number(couponId) : undefined
        })
        
        if (orderResponse.success) {
          // 后端返回的是订单号字符串，需要解析订单信息
          orderData.value = {
            orderId: 0, // 需要从后端获取，暂时设为0
            orderNo: orderResponse.data,
            totalAmount: 0, // 需要从后端获取，暂时设为0
            discountAmount: 0,
            actualAmount: 0,
            createdAt: new Date().toISOString(),
            expireTime: new Date(Date.now() + 30 * 60 * 1000).toISOString() // 30分钟后过期
          }
          
          // 获取用户余额
          const balanceResponse = await getAccountBalance()
          if (balanceResponse.success) {
            userBalance.value = balanceResponse.data
            // 如果余额充足，默认选择余额支付
            if (canUseBalance.value) {
              selectedPaymentMethod.value = 'BALANCE'
            }
          }
        } else {
          throw new Error(orderResponse.message || '创建订单失败')
        }
      } catch (err) {
        error.value = err instanceof Error ? err.message : '加载订单信息失败'
      } finally {
        loading.value = false
      }
    }

    // 开始倒计时
    const startCountdown = () => {
      if (countdownTimer.value) {
        clearInterval(countdownTimer.value)
      }
      
      countdownTimer.value = setInterval(() => {
        if (remainingTime.value > 0) {
          remainingTime.value--
        } else {
          clearInterval(countdownTimer.value as number)
          ElMessage.warning('订单已超时，请重新下单')
          router.back()
        }
      }, 1000) as unknown as number
    }

    // 支付方式改变
    const onPaymentMethodChange = () => {
      // 切换支付方式时清除二维码
      qrCodeUrl.value = ''
    }

    // 生成支付宝二维码
    const generateAlipayQrCode = async () => {
      if (!orderData.value.orderNo) {
        ElMessage.error('订单信息错误')
        return
      }

      processingPayment.value = true
      try {
        const response = await payOrder(orderData.value.orderNo, {
          paymentMethod: 'ALIPAY',
          returnUrl: window.location.origin + '/payment/success',
          notifyUrl: window.location.origin + '/api/payment/notify'
        })
        
        if (response.success && response.data.paymentUrl) {
          qrCodeUrl.value = response.data.paymentUrl
          // 开始轮询支付结果
          pollPaymentStatus()
        } else {
          throw new Error(response.message || '生成支付二维码失败')
        }
      } catch (err) {
        ElMessage.error(err instanceof Error ? err.message : '生成二维码失败')
      } finally {
        processingPayment.value = false
      }
    }

    // 处理余额支付
    const handleBalancePayment = async () => {
      if (!orderData.value.orderNo) {
        ElMessage.error('订单信息错误')
        return
      }

      if (!canUseBalance.value) {
        ElMessage.warning('余额不足，请充值后再试')
        return
      }

      processingPayment.value = true
      try {
        const response = await payOrder(orderData.value.orderNo, {
          paymentMethod: 'BALANCE'
        })
        
        if (response.success) {
          // 显示支付成功
          paymentResult.value = {
            show: true,
            success: true,
            title: '支付成功',
            message: response.data.message || '订单支付成功！',
            detail: `订单号: ${response.data.orderNo || orderData.value.orderNo}`
          }
        } else {
          throw new Error(response.message || '余额支付失败')
        }
      } catch (err) {
        // 显示支付失败
        paymentResult.value = {
          show: true,
          success: false,
          title: '支付失败',
          message: err instanceof Error ? err.message : '余额支付失败',
          detail: ''
        }
      } finally {
        processingPayment.value = false
      }
    }

    // 轮询支付状态（用于支付宝等异步支付方式）
    let pollTimer: number | null = null
    const pollPaymentStatus = () => {
      if (pollTimer) {
        clearInterval(pollTimer)
      }
      
      let pollCount = 0
      const maxPollCount = 60 // 最多轮询60次（约5分钟）
      
      pollTimer = setInterval(async () => {
        if (pollCount >= maxPollCount) {
          clearInterval(pollTimer as number)
          ElMessage.warning('支付超时，请刷新页面重试')
          return
        }
        
        try {
          // 这里应该调用一个查询订单支付状态的API
          // 为简化示例，这里暂时不实现具体的查询逻辑
          console.log('轮询支付状态...', pollCount)
          pollCount++
        } catch (err) {
          console.error('轮询支付状态失败:', err)
        }
      }, 5000) as unknown as number // 每5秒轮询一次
    }

    // 处理支付结果对话框关闭
    const handleResultClose = () => {
      paymentResult.value.show = false
      
      if (paymentResult.value.success) {
        // 支付成功后跳转到订单详情或成功页面
        router.push({ path: '/orders/detail', query: { orderNo: orderData.value.orderNo } })
      }
    }

    // 生命周期钩子
    onMounted(() => {
      loadOrderInfo()
    })

    onBeforeUnmount(() => {
      // 清理定时器
      if (countdownTimer.value) {
        clearInterval(countdownTimer.value)
      }
      if (pollTimer) {
        clearInterval(pollTimer)
      }
    })

    return {
      loading,
      error,
      orderData,
      userBalance,
      selectedPaymentMethod,
      processingPayment,
      qrCodeUrl,
      remainingTime,
      paymentResult,
      canUseBalance,
      formatDate,
      formatTime,
      loadOrderInfo,
      onPaymentMethodChange,
      generateAlipayQrCode,
      handleBalancePayment,
      handleResultClose
    }
  }
})
</script>

<style scoped>
.order-payment-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.payment-header {
  margin-bottom: 30px;
}

.payment-header h2 {
  margin-bottom: 10px;
  color: #303133;
}

.breadcrumb {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.breadcrumb-item {
  margin-right: 8px;
  margin-left: 8px;
}

.breadcrumb-item:first-child {
  margin-left: 0;
}

.breadcrumb-item.active {
  color: #409eff;
  font-weight: 500;
}

.payment-card {
  margin-bottom: 20px;
}

.loading-container,
.error-container {
  padding: 40px 0;
  text-align: center;
}

.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.payment-content {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.order-info-section,
.payment-method-section,
.balance-payment-section,
.alipay-payment-section {
  padding: 20px;
  background-color: #fafafa;
  border-radius: 4px;
}

.order-info-section h3,
.payment-method-section h3 {
  margin-bottom: 20px;
  color: #303133;
  font-size: 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.info-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.info-item .label {
  color: #606266;
  font-size: 14px;
}

.info-item .value {
  color: #303133;
  font-size: 14px;
}

.info-item .value.amount {
  color: #f56c6c;
  font-size: 20px;
  font-weight: 500;
}

.info-item .value.discount {
  color: #67c23a;
}

.info-item .value.balance {
  color: #409eff;
}

.info-item .value.countdown {
  color: #e6a23c;
  font-weight: 500;
}

.info-item .value.countdown.time-warning {
  color: #f56c6c;
}

.balance-warning {
  margin-top: 10px;
  color: #f56c6c;
  font-size: 14px;
}

.confirm-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.qr-code-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  margin: 20px 0;
}

.qr-code {
  width: 200px;
  height: 200px;
}

.loading-qr,
.qr-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  color: #606266;
}

.payment-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}

.payment-result-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.result-icon {
  font-size: 48px;
  margin-bottom: 20px;
}

.result-icon.success {
  color: #67c23a;
}

.result-icon.error {
  color: #f56c6c;
}

.result-message {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 10px;
}

.result-detail {
  color: #909399;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}
</style>